<template>
  <div class="publicpageview">
    <div class="publicformview">
      <el-form :inline="true" :model="listQuery" size="mini" ref="searchForm">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="用户名：" prop="keyword">
              <el-input v-model="listQuery.keyword"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="手机号码：" prop="phone">
              <el-input v-model="listQuery.phone"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="状态：" prop="status">
              <el-select v-model="listQuery.status" clearable>
                <el-option label="启用" value="1" key="1"></el-option>
                <el-option label="禁用" value="0" key="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="4">
            <el-form-item label="部门：" prop="status">
              <el-select v-model="listQuery.status">
                <el-option label="发布" value="1" key="1"></el-option>
                <el-option label="不发布" value="0" key="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="4">
            <div>
              <el-button size="mini" type="primary" @click="getList">查询</el-button>
              <el-button size="mini" @click="pageNum = 1;resetForm('searchForm')">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="publitableview">
      <el-button type="primary" size="mini" @click="handleAddUser('add')">新增用户</el-button>
      <el-table :data="list" border fit highlight-current-row size="mini">
        <el-table-column align="center" label="用户编号" prop="uid">
        </el-table-column>

        <el-table-column align="center" label="组织结构名称" prop="organizational">
        </el-table-column>

        <el-table-column align="center" label="用户名" prop="username">
        </el-table-column>
				
        <el-table-column align="center" label="企业微信ID" prop="wechatId">
        </el-table-column>

        <el-table-column align="center" label="手机号码" prop="phone">
        </el-table-column>
        <el-table-column align="center" label="状态" prop="status">
          <template slot-scope="scope">
            <span>{{ scope.row.status == 1 ? "启用" : "禁用" }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" label="部门" prop="deptId">
          <template slot-scope="scope">
            <span>{{ deptName(scope.row.deptId) }}</span>
          </template>
        </el-table-column> -->

        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleUpdate(scope.row, 'quanxian')">数据权限</el-button>

            <el-button type="text" size="mini" @click="handleUpdate(scope.row, 'update')">修改</el-button>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row,'details')">详情</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.uid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="publicpaginationview">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.pageNum" background :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total" small></el-pagination>
      </div>
    </div>

    <el-dialog :title="isAdd == 'add' ? '新增用户' : isAdd == 'update' ? '修改用户' : '用户详情'" :visible.sync="dialogVisible"
      width="40%" :before-close="handleClose">
      <el-form :model="formData" ref="dataForm" class="demo-ruleForm" label-position="right" label-width="120px"
        size="mini" :rules="rules">
        <el-form-item label="用户编号：" prop="uid">
          <el-input v-model="formData.uid" disabled></el-input>
        </el-form-item>

        <el-form-item label="市房管中心" prop="organizational">
          <el-input v-model="formData.organizational" disabled></el-input>
        </el-form-item>
        <el-form-item label="区：" prop="districtId">
          <el-select v-model="formData.districtId" @change="handleFormQuchange">
            <el-option v-for="item in areaList" :label="item.dname" :value="item.did" :key="item.did"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="部门：" prop="houseAdminId">
          <el-select v-model="formData.houseAdminId" @change="handleBuchange">
            <el-option v-for="item in houseFormAdminList" :label="item.aname" :value="item.aid"
              :key="item.aid"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业微信ID：" prop="wechatId">
          <el-input v-model="formData.wechatId"></el-input>
        </el-form-item>
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：" prop="phone">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>

        <!-- <el-form-item label="归属部门：" prop="deptId">
          <el-select v-model="formData.deptId">
            <el-option label="事业部" value="1" key="1"></el-option>
            <el-option label="生活部" value="0" key="0"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="用户密码：" prop="password">
          <el-input v-model="formData.password" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="checkPass">
          <el-input v-model="formData.checkPass" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属角色：" prop="roleid">
          <el-select v-model="formData.roleid">
            <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in roleList"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态：" prop="status">
          <el-select v-model="formData.status">
            <el-option label="启用" value="1" key="1"></el-option>
            <el-option label="禁用" value="0" key="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注：" prop="note">
          <el-input v-model="formData.note" type="textarea" :rows="2"></el-input>
        </el-form-item>
      </el-form>

      <div class="treeview" v-if="isAdd == 'quanxian'">
        <span>权限控制： </span>
        <div style="flex: 1;">
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
            :indeterminate="isIndeterminate">全选/全不选</el-checkbox>
          <div class="tree">
            <el-tree ref="tree" node-key="specialid" show-checkbox :data="treeData" :props="defaultProps"
              @check="handleCheckChange" :default-checked-keys="checkedList">
              <template #default="{ node, data }">
                {{ data.dname}}

              </template>
            </el-tree>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false" size="medium" v-if="isAdd == 'details'">返 回</el-button>

        <el-button type="primary" @click="save" size="medium" v-else>保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
let arr = [];
import { userList, listAll, registerUser, updateUser, deleteUser, listUsersData, allowUsersData } from '@/api/system'
import { districtHouseAdminInfo, getArea, getHouseAdmin } from '@/api/common'
// import { , getHouseAdmin, getBlockGroup, getBlockByGroup, upload } from '@/api/common'
import { Message } from 'element-ui'
export default {
  name: "AccommodationManagementIndex",

  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.formData.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }

    };
    return {
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        keyword: "",
        phone: "",
        status: "",
      },
      rules: {

        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],

      },
      total: 0,
      list: [],
      dialogVisible: false,
      isAdd: 'add',
      roleList: [],
      areaList: [],
      houseFormAdminList: [],
      isIndeterminate: false,
      defaultProps: {
        children: 'houseAdminList',
        label: 'dname'
      },

      checkAll: false,
      checkedList: [], //当前选择的树keys
      treeData: [],
      bustr: "",
      qustr: "",
      formData: {
        uid: "",
        username: "",
        phone: "",
        deptId: "",
        roleid: "",
        status: "",
        note: "",
        password: "",
        checkPass: "",
        houseAdminId: "",
        districtId: "",
        organizational: "市房管中心",
				wechatId:""
      },
    };
  },

  computed: {
    deptName() {
      return (val) => {
        if (val == "1") {
          return "事业部";
        }
        return "生活部";
      };
    },
  },

  beforeDestroy() {
    arr = []
  },

  mounted() {
    this.getCommon();
    this.getList();
    this.listAll();
    this.getdistrictHouseAdminInfo();
  },

  methods: {

    getCommon() {
      getArea().then(res => {
        this.areaList = res.data
      })
    },

    handleFormQuchange(val) {
      this.formData.houseAdminId = null;


      if (val) {
        this.areaList.forEach(i => {
          if (i.did == val) {
            this.qustr = i.dname;
            this.bustr = ""
          }
        })

        this.getFormHouseAdmin(val);

      } else {
        this.houseFormAdminList = [];
        this.qustr = "";
        this.bustr = "";
      }

      this.formData.organizational = "市房管中心" + this.qustr + this.bustr
    },

    handleBuchange(val) {
      if (val) {
        this.houseFormAdminList.forEach(i => {
          if (i.aid == val) {
            this.bustr = i.aname
          }
        })

      } else {
        this.bustr = "";
      }
      this.formData.organizational = "市房管中心" + this.qustr + this.bustr
    },

    getFormHouseAdmin(val) {
      getHouseAdmin({ DID: val, pageNum: 1, pageSize: 100000 }).then(res => {
        this.houseFormAdminList = res.data.list;
      })
    },
    getdistrictHouseAdminInfo() {
      districtHouseAdminInfo().then(res => {
        let arrlist = [];
        res.data.forEach(i => {
          if (i.houseAdminList.length > 0) {
            arrlist.push(i)
          }
        })
        this.treeData = [...arrlist];
        this.getAllCheckKeys(this.treeData)
      })
    },

    getAllCheckKeys(option) {
      option.forEach(item => {

        if (item.houseAdminList) {
          // this.getAllCheckKeys(item.houseAdminList)
          item.houseAdminList.forEach(i => {
            arr.push(i.specialid)
          })
        }
      })

    },

    handleCheckChange(data, checked, checkNode) {
      this.checkedList = checked.checkedKeys;
      if (arr.length == 0) {
        this.checkAll = false;
        this.isIndeterminate = false;
      } else {
        if (this.checkedList.length == 0) {
          this.checkAll = false;
          this.isIndeterminate = false;
        } else {

          if (arr.length == this.checkedList.length) {

            this.checkAll = true;
            this.isIndeterminate = false;
          }
          if (arr.length > this.checkedList.length) {


            this.checkAll = false;
            this.isIndeterminate = true;
          }
        }


      }
    },



    handleCheckAllChange() {
      if (arr.length != 0) {
        if (this.checkedList.length != 0) {
          if (this.checkedList.length == arr.length) {
            this.checkAll = false;
            this.$refs.tree.setCheckedKeys([]);
            this.checkedList = []
          } else {
            this.checkAll = true;
            this.isIndeterminate = false;
            this.$refs.tree.setCheckedKeys(arr);
            this.checkedList = arr;
          }
        } else {
          this.checkAll = true;
          this.isIndeterminate = false;
          this.$refs.tree.setCheckedKeys(arr);
          this.checkedList = arr;
        }
      } else {
        this.checkAll = false;
        this.isIndeterminate = false;
      }
    },

    save() {

      if (this.formData.password != this.formData.checkPass) return
      if (this.isAdd == 'add') {
        registerUser({ ...this.formData }).then(res => {

          Message({
            message: res.message || '操作成功',
            type: "success",
            duration: 3 * 1000,
          });
          tthis.handleClose();
          this.getList();
        })
      }

      if (this.isAdd == 'update' || this.isAdd == 'quanxian') {
        updateUser({ ...this.formData }).then(res => {
          if (this.isAdd == 'quanxian') {
            let houseAdminList = this.$refs.tree.getCheckedNodes(true);
            allowUsersData({ districtList: [], houseAdminList, userId: this.formData.uid })
          }
          Message({
            message: res.message || '操作成功',
            type: "success",
            duration: 3 * 1000,
          });
          this.handleClose();
          this.getList();
        })
      }




    },
    listAll() {
      listAll({
        pageNum: 1,
        pageSize: 100000
      }).then(res => {
        this.roleList = res.data.list
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    getList() {
      userList(this.listQuery).then((response) => {
        this.total = response.data.total;
        this.list = response.data.list;
      });
    },

    resetForm(val) {

      this.$refs[val].resetFields();
    },

    handleAddUser(type) {
      this.isAdd = 'add';
      this.dialogVisible = true;
      this.checkedList = [];
    },

    handleClose() {
      this.resetForm("dataForm");
      this.dialogVisible = false;
      this.checkedList = [];

      this.isIndeterminate = false;
      this.houseFormAdminList = [];
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys(this.checkedList);
      }
    },

    handleUpdate(currentData, type) {
      this.isAdd = type;
      this.dialogVisible = true;
      this.handleFormQuchange(currentData.districtId)
      this.$nextTick(() => {
        this.formData = { ...currentData, status: String(currentData.status), checkPass: currentData.password, organizational: currentData.organizational ? currentData.organizational : "市房管中心" };
      });
      if (type == 'quanxian') {
        listUsersData(currentData.uid).then(res => {
          let arrlist = [];

          if (res.data.houseAdminList != null) {
            res.data.houseAdminList.forEach(i => {
              arrlist.push(i.specialid)
            })
          }

          this.checkedList = arrlist
          if (arr.length != 0) {
            if (this.checkedList.length != 0) {


              if (this.checkedList.length == arr.length) {

                this.checkAll = true;
                this.isIndeterminate = false;
                this.$refs.tree.setCheckedKeys(arr);
              } else {
                this.checkAll = false;
                this.isIndeterminate = true;
                this.$refs.tree.setCheckedKeys(this.checkedList);
              }
            } else {
              this.checkAll = false;
              this.isIndeterminate = false;
            }
          } else {
            this.checkAll = false;
            this.isIndeterminate = false;
          }
        })
      }



    },

    handleDelete(id) {
      this.$confirm(
        "此操作将删除该条内容，请确认是否继续操作？",
        "删除提示",
        {
          confirmButtonText: "保 存",
          cancelButtonText: "取 消",
          type: "warning",
        }
      )
        .then(() => {
          deleteUser(id).then(res => {
            Message({
              message: res.message || '操作成功',
              type: "success",
              duration: 3 * 1000,
            });
            this.getList();
          })
        })
        .catch(() => { });
    }
  },
};
</script>

<style scoped>
.treeview {
  width: 100%;
  background: #F7F7F7;
  display: flex;
  padding-bottom: 20px;
  padding-top: 20px;

  span {
    color: #008c93;
    width: 120px;
    text-align: right;
    display: inline-block;
    /* margin-right: 4px; */
    box-sizing: border-box;
    padding-right: 12px;
  }

  margin-top: 20px;
}
</style>